<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="帖子" prop="postId">
        <el-select v-model="queryParams.postId" placeholder="请选择帖子" clearable @change="handlePostChange">
          <el-option
            v-for="post in postOptions"
            :key="post.postId"
            :label="post.title"
            :value="post.postId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评论内容" prop="content">
        <el-input
          v-model="queryParams.content"
          placeholder="请输入评论内容"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['community:comment:add']"
          :disabled="!queryParams.postId"
        >新增评论</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['community:comment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['community:comment:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="commentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="评论ID" align="center" prop="commentId" />
      <el-table-column label="帖子ID" align="center" prop="postId" />
      <el-table-column label="评论内容" align="center" prop="content" :show-overflow-tooltip="true" />
      <el-table-column label="评论人" align="center" prop="createBy" />
      <el-table-column label="点赞数" align="center" prop="likes" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ scope.row.status === '0' ? '正常' : '停用' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-chat-dot-round"
            @click="handleReply(scope.row)"
            v-hasPermi="['community:comment:add']"
          >回复</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['community:comment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['community:comment:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改评论对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="评论内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="4"
            :placeholder="form.parentId ? '请输入回复内容' : '请输入评论内容'"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 回复评论对话框 -->
    <el-dialog :title="'回复评论'" :visible.sync="replyOpen" width="500px" append-to-body>
      <div class="reply-content">
        <div class="original-comment">
          <p><strong>原评论：</strong></p>
          <p>{{ replyToComment.content }}</p>
        </div>
      </div>
      <el-form ref="replyForm" :model="replyForm" :rules="rules" label-width="80px">
        <el-form-item label="回复内容" prop="content">
          <el-input
            v-model="replyForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReply">确 定</el-button>
        <el-button @click="cancelReply">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listComment, getComment, delComment, addComment, updateComment, listPost } from "@/api/business/comment";

export default {
  name: "Comment",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 评论表格数据
      commentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 帖子选项
      postOptions: [],
      // 评论选项
      commentOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        postId: null,
        content: null,
        status: null
      },
      // 表单参数
      form: {},
      // 是否显示回复弹出层
      replyOpen: false,
      // 回复的评论信息
      replyToComment: {},
      // 回复表单参数
      replyForm: {},
      // 表单校验
      rules: {
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      },
      // 当前选中的帖子
      currentPost: null
    };
  },
  created() {
    // 先获取帖子列表
    this.getPostOptions();
    // 获取评论列表
    this.getList();
  },
  methods: {
    /** 获取帖子列表 */
    getPostOptions() {
      listPost().then(response => {
        this.postOptions = response.rows;
      });
    },
    /** 处理帖子选择变化 */
    handlePostChange(postId) {
      if (postId) {
        this.currentPost = this.postOptions.find(item => item.postId === postId);
      } else {
        this.currentPost = null;
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 查询评论列表 */
    getList() {
      this.loading = true
      listComment(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.commentList = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取评论选项
    getCommentOptions(postId) {
      if (!postId) return;
      listComment({ postId: postId }).then(response => {
        this.commentOptions = response.rows;
      });
    },
    // 处理父评论变化
    handleParentChange(val) {
      if (val) {
        const parentComment = this.commentOptions.find(item => item.commentId === val);
        if (parentComment) {
          this.form.replyTo = parentComment.userId;
        }
      } else {
        this.form.replyTo = null;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        commentId: null,
        postId: this.queryParams.postId,  // 使用当前选中的帖子ID
        content: null,
        parentId: null,
        replyTo: null,
        status: "0"
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.commentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (!this.queryParams.postId) {
        this.$modal.msgError("请先选择帖子");
        return;
      }
      this.reset();
      this.open = true;
      this.title = "添加评论";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const commentId = row.commentId || this.ids;
      getComment(commentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改评论";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.commentId != null) {
            updateComment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addComment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const commentIds = row.commentId || this.ids;
      this.$modal.confirm('是否确认删除评论编号为"' + commentIds + '"的数据项？').then(function() {
        return delComment(commentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 回复表单重置
    resetReply() {
      this.replyForm = {
        postId: this.queryParams.postId,  // 使用当前选中的帖子ID
        content: null,
        parentId: this.replyToComment.commentId,
        replyTo: this.replyToComment.userId
      };
      this.resetForm("replyForm");
    },
    /** 回复按钮操作 */
    handleReply(row) {
      if (!this.queryParams.postId) {
        this.$modal.msgError("请先选择帖子");
        return;
      }
      this.replyToComment = row;
      this.resetReply();
      this.replyOpen = true;
    },
    // 取消回复
    cancelReply() {
      this.replyOpen = false;
      this.resetReply();
    },
    // 提交回复
    submitReply() {
      this.$refs["replyForm"].validate(valid => {
        if (valid) {
          addComment(this.replyForm).then(response => {
            this.$modal.msgSuccess("回复成功");
            this.replyOpen = false;
            this.getList();
          });
        }
      });
    }
  }
};
</script>
